import 'package:flutter/material.dart';
import 'package:ok_github/page/error/error_page.dart';
import 'package:ok_github/page/home/home_page.dart';
import 'package:ok_github/page/login/login_page.dart';
import 'package:ok_github/page/message/message_page.dart';
import 'package:ok_github/page/route/route_observer.dart';

RouteConfig routes = RouteConfig();

class RouteConfig {
  static RouteConfig _instance;

  RouteConfig._() {
    initRoutes();
  }

  factory RouteConfig() {
    if (_instance == null) {
      _instance = RouteConfig._();
    }
    return _instance;
  }

  final login = "/login";
  final notification = "/notification";
  final home = "/home";

  MyRouteObserver observer = MyRouteObserver();

  void initRoutes() {}

  PageRoute getRoute(RouteSettings settings) {
    return _RouteFactory(settings).createRoute();
  }
}

abstract class _Route {
  String get baseUrl;

  Widget buildPage(List<String> routeList);
}

class _RouteFactory {
  final RouteSettings settings;

  String get name => settings.name;

  _RouteFactory(this.settings);

  PageRoute createRoute() {
    try {
      if (name == "/") {
        return buildRoute(LoginPage());
      }

      if (!name.startsWith("/")) {
        return buildRoute(NoFoundPage());
      }

      var routeList = name.split("/");
      var level1 = routeList[1];
//      print("level1 = [$level1]");

      if (level1 == "") {
        return buildRoute(LoginPage());
      }

      Widget page = _findRoute(level1)?.buildPage(routeList) ?? NoFoundPage();

      return buildRoute(page);
    } catch (e) {
      return buildRoute(NoFoundPage());
    }
  }

  _Route _findRoute(String baseUrl) {
    for (var route in _routeList) {
      if (route.baseUrl == baseUrl) {
        return route;
      }
    }
    return null;
  }

  PageRoute buildRoute(Widget widget) {
    return MaterialPageRoute(
      builder: (BuildContext context) {
        return widget;
      },
      settings: settings,
    );
  }

  List<_Route> _routeList = [LoginRoute(), HomeRoute(), NotificationRoute()];
}

class LoginRoute implements _Route {
  @override
  String get baseUrl => "login";

  @override
  Widget buildPage(List<String> routeList) {
    if (routeList.length == 2) {
      return LoginPage();
    }
    return null;
  }
}

class HomeRoute implements _Route {
  @override
  String get baseUrl => "home";

  @override
  Widget buildPage(List<String> routeList) {
    if (routeList.length == 2) {
      return HomePage();
    }
    return null;
  }
}

class NotificationRoute implements _Route {
  @override
  String get baseUrl => "notification";

  @override
  Widget buildPage(List<String> routeList) {
    if (routeList.length == 2) {
      return NotificationPage();
    }
    return null;
  }
}
